﻿app.controller('FacAndEquController', function ($scope, $http, $window, $compile, $filter, ipCookie, common, option, Upload) {
    $scope.result = {};
    $scope.dateOption = option.date;
    $scope.datetimeOption = option.datetime;

    $scope.InitDatePicker = function (control) {
        (function ($) {
            $.init();
            var btns = $(control);
            btns.each(function (i, btn) {
                btn.addEventListener('tap', function () {
                    var _self = this;
                    if (_self.picker) {
                        _self.picker.show(function (rs) {
                            jQuery(control).val(rs.text);
                            _self.picker.dispose();
                            _self.picker = null;
                        });
                    } else {
                        var optionsJson = this.getAttribute('data-options') || '{}';
                        var options = JSON.parse(optionsJson);
                        var id = this.getAttribute('id');
                        _self.picker = new $.DtPicker(options);
                        _self.picker.show(function (rs) {
                            jQuery(control).val(rs.text);
                            console.log($scope.AddModel);
                            _self.picker.dispose();
                            _self.picker = null;
                        });
                    }
                }, false);
            });
        })(mui);
    }

    $scope.GetDeviceList = function (model, page) {
        $scope.PageLoading = true;
        $scope.DeviceList = [];
        $http({
            method: 'POST',
            url: '../FacilityAndEquipment/GetFacilityPageList',
            data: { "model": model },
            params: { 'page': page }
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $scope.DeviceList = ret.Data.Data;
                    $scope.TotalCount = ret.Data.TotalItemCount;
                    $scope.PageLoading = false;
                }
                else {
                    alertify.alert(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }

    $scope.InitPlaceEqu = function () {
        setTimeout(function () {
            $scope.InitFireFacilityFormList();
        }, 1000);
    }

    $scope.MGetDeviceList = function (model, page) {
        if (page == 1) {
            $scope.DataList = [];
        }
        $scope.PageIndex = page;
        $http({
            method: 'POST',
            url: '../FacilityAndEquipment/GetFacilityPageList',
            data: { 'model': model },
            params: { 'page': page }
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $scope.TotalCount = ret.Data.TotalItemCount;
                    for (var i = 0; i < ret.Data.Data.length; i++) {
                        $scope.DataList.push(ret.Data.Data[i]);
                    }
                    if (ret.Data.Data.length == 0) {
                        mui('#pullrefresh').pullRefresh().endPullupToRefresh(true);
                    }
                    else {
                        mui('#pullrefresh').pullRefresh().endPullupToRefresh(false);
                    }

                    console.log($scope.DataList);
                }
                else {
                    mui.toast(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }

    $scope.InitFireFacilityFormList = function () {
        $scope.PageIndex = 1;
        mui.init({
            pullRefresh: {
                container: '#pullrefresh',
                down: {
                    style: 'circle',
                    auto: true,//可选,默认false.首次加载自动上拉刷新一次
                    callback: function () {
                        setTimeout(function () {
                            $scope.MGetDeviceList($scope.SearchModel, 1);
                            mui('#pullrefresh').pullRefresh().refresh(true);
                            mui('#pullrefresh').pullRefresh().endPulldownToRefresh();
                        }, 1500);

                    }
                }, up: {
                    auto: false,
                    contentrefresh: '正在加载...',
                    callback: function () {
                        $scope.MGetDeviceList($scope.SearchModel, $scope.PageIndex + 1);
                    },

                }
            }
        });
    }
    $scope.GetParkList = function () {
        $scope.ParkList = [];
        $http({
            method: 'POST',
            url: '../SafetyConfig/GetParkList'
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $scope.ParkList = ret.Data;
                }
                else {
                    alertify.alert(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }

    $scope.GetPlaceList = function (control, id, defaultvalue) {
        if (id == null || id == "")
            return false;
        if (defaultvalue == null) {
            $("#" + control).html($compile('<option value="" selected>请选择场所</option>')($scope));
            $("#" + control).selectpicker('refresh');
        }
        $http({
            method: 'POST',
            url: '../IssueReport/GetParkPlace',
            data: { "ParkId": id }
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $.each(ret.Data, function (i, n) {
                        if (defaultvalue != null) {
                            if (n.RoomId == defaultvalue)
                                $("#" + control).append($compile("<option selected='selected' value=\"" + n.RoomId + "\">" + n.PlaceName + "</option>")($scope));
                            else
                                $("#" + control).append($compile("<option value=\"" + n.RoomId + "\">" + n.PlaceName + "</option>")($scope));
                        }
                        else {
                            $("#" + control).append($compile("<option value=\"" + n.RoomId + "\">" + n.PlaceName + "</option>")($scope));
                        }
                    })
                    $("#" + control).selectpicker('refresh');
                    $("#" + control).selectpicker('render');
                }
                else {
                    alertify.alert(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
        if (defaultvalue != null) {
            $("#" + control).val(defaultvalue);
            $("#" + control).selectpicker('refresh');
            $("#" + control).selectpicker('render');
        }
    }

    $scope.GetDepartmentList = function (id) {
        $scope.DepartmentList = [];
        $http({
            method: 'POST',
            url: '../CheckForm/GetDepartmentList'
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $scope.DepartmentList = ret.Data;
                }
                else {
                    alertify.alert(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }

    $scope.GetDeviceTypeList = function (id) {
        $scope.DeviceTypeList = [];
        $http({
            method: 'POST',
            url: '../FacilityAndEquipment/GerDeviceType'
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $scope.DeviceTypeList = ret.Data;
                }
                else {
                    alertify.alert(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }

    $scope.GetCompanyList = function (id) {
        $scope.CompanyList = [];
        $http({
            method: 'POST',
            url: '../FacilityAndEquipment/GetMaintenanceCompanyList'
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $scope.CompanyList = ret.Data;
                }
                else {
                    alertify.alert(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }

    $scope.refreshOption = function (control) {
        $("#" + control).selectpicker('refresh');
    }

    $scope.BindDepartmentList = function (control, defaultvalue) {
        $http({
            method: 'POST',
            url: '../HiddenTrouble/GetDepartmentList'
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $.each(ret.Data, function (i, n) {
                        if (n.DepartmentName != "系统支持") {
                            if (defaultvalue != null) {
                                if (n.Id == defaultvalue)
                                    $("#" + control).append($compile("<option selected='selected' value=\"" + n.Id + "\">" + n.DepartmentName + "</option>")($scope));
                                else
                                    $("#" + control).append($compile("<option value=\"" + n.Id + "\">" + n.DepartmentName + "</option>")($scope));
                            }
                            else {
                                $("#" + control).append($compile("<option value=\"" + n.Id + "\">" + n.DepartmentName + "</option>")($scope));
                            }
                        }
                    })
                    $("#" + control).selectpicker('refresh');
                }
                else {
                    alertify.alert(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }

    $scope.AddDeiveForm = function (model,pagename) {
        if (model.DepartmentId == null || model.DepartmentId == "") {
            alertify.alert("请选择管理部门");
            return false;
        }
        $http({
            method: 'POST',
            url: '../FacilityAndEquipment/AddEquAndFac',
            data: { 'model': model},
        })
            .success(function (ret) {
                if (ret.Code == 100) {
                    alertify.alert("数据添加成功");

                    setTimeout(function () {
                        location.href = decodeURIComponent(pagename);
                    }, 2000)
                } else
                    alertify.alert(ret.Msg);
            })
            .error(function (data, status, headers, config) {
                common.error($scope);
            })
    }

    $scope.EditDeiveForm = function (model,pagename,page) {
        if (model.DepartmentId == null || model.DepartmentId == "") {
            alertify.alert("请选择管理部门");
            return false;
        }
        $http({
            method: 'POST',
            url: '../FacilityAndEquipment/EditEquAndFac',
            data: { 'model': model },
        })
            .success(function (ret) {
                if (ret.Code == 100) {
                    alertify.alert("数据更新成功");

                    setTimeout(function () {
                        location.href = decodeURIComponent(pagename);
                    }, 2000)
                } else
                    alertify.alert(ret.Msg);
            })
            .error(function (data, status, headers, config) {
                common.error($scope);
            })
    }

    $scope.GetDeviceInfo = function (id) {
        $scope.DataModel = {};
        $http({
            method: 'POST',
            url: '../FacilityAndEquipment/GetEquAndFac',
            data: { 'Id': id }
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $scope.DataModel = ret.Data;
                    $scope.DataModel.ParkId = $scope.DataModel.ParkId + "";
                    $scope.DataModel.CompanyId = $scope.DataModel.CompanyId + "";
                    $scope.DataModel.Status = $scope.DataModel.Status + "";
                    $scope.DataModel.DeviceType = $scope.DataModel.DeviceType + "";
                    $scope.BindDepartmentList('dep_select', $scope.DataModel.DepartmentId);
                    $scope.DataModel.CreateTime = $filter('JSONDate')($scope.DataModel.CreateTime, 'yyyy-MM-dd HH:mm:ss');
                    if ($scope.DataModel.NextMaintainceDate != null) {
                        $scope.DataModel.NextMaintainceDate = $filter('JSONDate')($scope.DataModel.NextMaintainceDate, 'yyyy-MM-dd');
                    }
                    $scope.GetPlaceList('placelist', $scope.DataModel.ParkId, $scope.DataModel.RoomId);
                }
                else {
                    alertify.alert(ret.Msg);
                    alertify.alert(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }

    $scope.GetCurrentDevice = function (model) {
        $scope.AddModel.DeviceId = model.Id;
        $scope.AddModel.CompanyId = model.CompanyId;
        $scope.AddModel.CompanyName = model.CompanyName;
    }

    $scope.AddMaintanceRecord = function (model,searchmodel,page) {
        $http({
            method: 'POST',
            url: '../FacilityAndEquipment/AddDeviceMaintance',
            data: { 'model': model },
        })
            .success(function (ret) {
                if (ret.Code == 100) {
                    alertify.alert("维保数据更新成功");
                    $scope.GetDeviceList(searchmodel,page);
                    $("#close").click();
                } else
                    alertify.alert(ret.Msg);
            })
            .error(function (data, status, headers, config) {
                common.error($scope);
            })
    }

    $scope.GetDeviceStatusList = function () {
        $scope.StatusList = [];
        $http({
            method: 'POST',
            url: '../FacilityAndEquipment/GetDeviceStatusList'
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $scope.StatusList = ret.Data;
                }
                else {
                    alertify.alert(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }

    $scope.GetDeviceTypeChart = function (id) {
        $http({
            method: 'POST',
            url: '../FacilityAndEquipment/GetDeviceCountByType',
            data: { "RoomId": id }
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    var datalist = ret.Data;
                    var myChart = echarts.init(document.getElementById('devicechart'));

                    var datalist = ret.Data;

                    var option = {
                        tooltip: {
                            trigger: 'item'
                        },
                        legend: {
                            orient: 'vertical',
                            left: 'left',
                            show: false
                        },
                        toolbox: {
                            show: false,
                            orient: 'vertical',
                            left: 'right',
                            top: 'center',
                            feature: {
                                saveAsImage: { show: true }
                            }
                        },
                        series: [
                            {
                                name: '',
                                type: 'pie',
                                radius: ['30%', '50%'],
                                label: {
                                    alignTo: 'labelLine',
                                    formatter: '{name|{b}}:{c}',
                                    minMargin: 5,
                                    edgeDistance: 3,
                                    lineHeight: 15,
                                    rich: {
                                        time: {
                                            fontSize: 10,
                                            color: '#999'
                                        }
                                    }
                                },
                                labelLine: {
                                    show: true
                                },
                                data: datalist,
                                itemStyle: {

                                }
                            }
                        ]
                    };
                    myChart.setOption(option);
                }
                else {
                    alertify.alert(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }

    $scope.GetEquDetail = function (id) {
        $scope.EquModel = {};
        $http({
            method: 'POST',
            url: '../FacilityAndEquipment/GetEquDetail',
            data: { "Id": id }
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $scope.EquModel = ret.Data;
                }
                else {
                    mui.toast(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }

    $scope.MAddMaintanceRecord = function (model, pagename,backurl) {
        model.MaintainceDate = $("#MaintainceDate").val();
        model.NextDate = $("#NextDate").val();
        model.CompanyId = $scope.EquModel.CompanyId;
        console.log(model);
        $http({
            method: 'POST',
            url: '../FacilityAndEquipment/AddDeviceMaintance',
            data: { 'model': model }
        })
            .success(function (ret) {
                if (ret.Code == 100) {
                    mui.alert('维保信息提交成功', '系统提醒', function () {
                        if (pagename != '') {
                            window.location.href = pagename;
                        }
                        else {
                            window.location.href = backurl;
                        }
                    });
                    
                } else
                    alertify.alert(ret.Msg);
            })
            .error(function (data, status, headers, config) {
                common.error($scope);
            })
    }
});
app.filter('GetStatus', function () { //可以注入依赖
    return function (text) {
        if (text == '0')
            return "未使用";
        else if (text == '1')
            return "使用中";

    }
});

app.filter('GetBoolStr', function () { //可以注入依赖
    return function (text) {
        if (text)
            return "使用中";
        else
            return "未使用";

    }
});
app.filter('GetWeekDay', function () {
    return function (enddate) {
        var endDate = new Date(enddate);
        var beginDate = new Date(endDate.getFullYear(), 0, 1);
        //星期从0-6,0代表星期天，6代表星期六
        var endWeek = endDate.getDay();
        if (endWeek == 0) endWeek = 7;
        var beginWeek = beginDate.getDay();
        if (beginWeek == 0) beginWeek = 7;
        //计算两个日期的天数差
        var millisDiff = endDate.getTime() - beginDate.getTime();
        var dayDiff = Math.floor((millisDiff + (beginWeek - endWeek) * (24 * 60 * 60 * 1000)) / 86400000);
        return Math.ceil(dayDiff / 7) + 1;
    }

});